/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * CrearTestFrame.java
 *
 * Created on 10-ene-2012, 0:54:11
 */
package occho.view;

import java.awt.Color;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.JOptionPane;
import javax.swing.JSpinner;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import occho.model.Asignatura;
import occho.model.FachadaGestionTest;
import occho.model.Pregunta;
import occho.model.Tema;
import occho.model.Usuario;
import occho.model.Test;
import occho.view.resources.Messages;

/**
 *
 * @author Jorge
 */
public class CrearTestFrame extends javax.swing.JInternalFrame implements Internacionalizable {

    private FachadaGestionTest fachada = null;
    private Usuario profesor = null;
    private OcchoView view = null;
    private DefaultMutableTreeNode top=null;
    private Date dateInicio;
    private Date dateFin;
    
    
    /** Creates new form CrearTestFrame
     * @param view 
     */
    public CrearTestFrame(OcchoView view) {
        initComponents();
        this.setTitle("Crear test");
        this.profesor = view.getUsuario();
        fachada = new FachadaGestionTest(profesor);
        this.view = view;
        preguntasTestTree.setEnabled(false);
        
        // Cargamos las asignaturas
        for (Asignatura asignatura : this.profesor.getAsignaturas()) {
            cbAsignaturas.addItem(asignatura);
        }
        
        setLenguaje();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        lbAsignatura = new javax.swing.JLabel();
        cbAsignaturas = new javax.swing.JComboBox();
        txtNombre = new javax.swing.JTextField();
        lbNombre = new javax.swing.JLabel();
        lbDescripcion = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txtDescripcion = new javax.swing.JTextArea();
        lbFechaInicio = new javax.swing.JLabel();
        lbFechaFin = new javax.swing.JLabel();
        lbHoraInicio = new javax.swing.JLabel();
        lbHoraFin = new javax.swing.JLabel();
        spHoraInicio = new javax.swing.JSpinner();
        spHoraFin = new javax.swing.JSpinner();
        jScrollPane3 = new javax.swing.JScrollPane();
        temasTree = new javax.swing.JTree();
        btnCrearTest = new javax.swing.JButton();
        jScrollPane4 = new javax.swing.JScrollPane();
        preguntasTestTree = new javax.swing.JTree();
        btnAddPregunta = new javax.swing.JButton();
        btnDeletePregunta = new javax.swing.JButton();
        dcFechaInicio = new datechooser.beans.DateChooserCombo();
        dcFechaFin = new datechooser.beans.DateChooserCombo();

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jTree1.setName("jTree1"); // NOI18N
        jScrollPane2.setViewportView(jTree1);

        setClosable(true);
        setName("Form"); // NOI18N
        setPreferredSize(new java.awt.Dimension(681, 560));

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(occho.OcchoApp.class).getContext().getResourceMap(CrearTestFrame.class);
        lbAsignatura.setText(resourceMap.getString("lbAsignatura.text")); // NOI18N
        lbAsignatura.setName("lbAsignatura"); // NOI18N

        cbAsignaturas.setName("cbAsignaturas"); // NOI18N
        cbAsignaturas.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbAsignaturasActionPerformed(evt);
            }
        });

        txtNombre.setText(resourceMap.getString("txtNombre.text")); // NOI18N
        txtNombre.setName("txtNombre"); // NOI18N

        lbNombre.setText(resourceMap.getString("lbNombre.text")); // NOI18N
        lbNombre.setName("lbNombre"); // NOI18N

        lbDescripcion.setText(resourceMap.getString("lbDescripcion.text")); // NOI18N
        lbDescripcion.setName("lbDescripcion"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        txtDescripcion.setColumns(20);
        txtDescripcion.setRows(5);
        txtDescripcion.setName("txtDescripcion"); // NOI18N
        jScrollPane1.setViewportView(txtDescripcion);

        lbFechaInicio.setText(resourceMap.getString("lbFechaInicio.text")); // NOI18N
        lbFechaInicio.setName("lbFechaInicio"); // NOI18N

        lbFechaFin.setText(resourceMap.getString("lbFechaFin.text")); // NOI18N
        lbFechaFin.setName("lbFechaFin"); // NOI18N

        lbHoraInicio.setText(resourceMap.getString("lbHoraInicio.text")); // NOI18N
        lbHoraInicio.setName("lbHoraInicio"); // NOI18N

        lbHoraFin.setText(resourceMap.getString("lbHoraFin.text")); // NOI18N
        lbHoraFin.setName("lbHoraFin"); // NOI18N

        spHoraInicio.setModel(new javax.swing.SpinnerDateModel());
        spHoraInicio.setName("spHoraInicio"); // NOI18N

        spHoraFin.setModel(new javax.swing.SpinnerDateModel(new java.util.Date(), null, null, java.util.Calendar.MINUTE));
        spHoraFin.setName("spHoraFin"); // NOI18N

		JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(spHoraInicio, "HH:mm a");
		spHoraInicio.setEditor(timeEditor);
		spHoraInicio.setValue(new Date()); 
		
		JSpinner.DateEditor timeEditor2 = new JSpinner.DateEditor(spHoraFin, "HH:mm a");
		spHoraFin.setEditor(timeEditor2);
		spHoraFin.setValue(new Date());
		
        jScrollPane3.setName("jScrollPane3"); // NOI18N

        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        temasTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        temasTree.setName("temasTree"); // NOI18N
        jScrollPane3.setViewportView(temasTree);

        btnCrearTest.setText(resourceMap.getString("btnCrearTest.text")); // NOI18N
        btnCrearTest.setName("btnCrearTest"); // NOI18N
        btnCrearTest.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCrearTestActionPerformed(evt);
            }
        });

        jScrollPane4.setName("jScrollPane4"); // NOI18N

        treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        preguntasTestTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        preguntasTestTree.setName("preguntasTestTree"); // NOI18N
        jScrollPane4.setViewportView(preguntasTestTree);

        btnAddPregunta.setText(resourceMap.getString("btnAddPregunta.text")); // NOI18N
        btnAddPregunta.setName("btnAddPregunta"); // NOI18N
        btnAddPregunta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddPreguntaActionPerformed(evt);
            }
        });

        btnDeletePregunta.setText(resourceMap.getString("btnDeletePregunta.text")); // NOI18N
        btnDeletePregunta.setName("btnDeletePregunta"); // NOI18N
        btnDeletePregunta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeletePreguntaActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(cbAsignaturas, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 220, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(272, 272, 272))
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(txtNombre, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 220, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(272, 272, 272))
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(layout.createSequentialGroup()
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(lbFechaFin)
                                    .add(lbFechaInicio))
                                .add(61, 61, 61)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                                    .add(dcFechaInicio, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 220, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                                    .add(dcFechaFin, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 220, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                                .add(18, 18, 18)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(lbHoraFin)
                                    .add(lbHoraInicio))
                                .add(27, 27, 27)
                                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                                    .add(spHoraFin, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)
                                    .add(spHoraInicio, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 185, Short.MAX_VALUE)))
                            .add(lbAsignatura)
                            .add(lbNombre))
                        .addContainerGap())
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane3, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 230, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(btnDeletePregunta, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE)
                            .add(btnAddPregunta, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 131, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(jScrollPane4, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 251, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap())
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                        .add(btnCrearTest)
                        .addContainerGap())
                    .add(layout.createSequentialGroup()
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 645, Short.MAX_VALUE)
                        .addContainerGap())
                    .add(layout.createSequentialGroup()
                        .add(lbDescripcion)
                        .addContainerGap(601, Short.MAX_VALUE))))
        );

        layout.linkSize(new java.awt.Component[] {jScrollPane3, jScrollPane4}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lbAsignatura)
                    .add(cbAsignaturas, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(lbNombre)
                    .add(txtNombre, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(lbDescripcion)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING)
                    .add(spHoraInicio)
                    .add(lbFechaInicio, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
                    .add(lbHoraInicio, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 20, Short.MAX_VALUE)
                    .add(dcFechaInicio, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                        .add(lbHoraFin, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .add(spHoraFin)
                        .add(lbFechaFin, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .add(dcFechaFin, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .add(46, 46, 46)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                            .add(jScrollPane3, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE)
                            .add(jScrollPane4, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 204, Short.MAX_VALUE))
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnCrearTest))
                    .add(layout.createSequentialGroup()
                        .add(btnAddPregunta)
                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                        .add(btnDeletePregunta)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void cbAsignaturasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbAsignaturasActionPerformed
    if(cbAsignaturas.getItemCount() >0 )
        createNodesTemas(top);
        repaint();
}//GEN-LAST:event_cbAsignaturasActionPerformed

private void btnCrearTestActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCrearTestActionPerformed
    if (checkFields()){
            try {
                this.view.setStatusMessageLabel("Conectando a la base de datos", Color.BLACK);
                //insertar test y preguntas en bbdd
                Set<Pregunta> setPregs = createSet(preguntasTestTree);
                Test t = new Test(txtNombre.getText(), txtDescripcion.getText(), dateInicio, dateFin);
                t.setPreguntas(setPregs);
                Asignatura a = (Asignatura) cbAsignaturas.getSelectedItem();
                if(fachada.insertarTest(t, a)){
                    //this.view.setStatusMessageLabel("Operación realizada", Color.BLACK);
                    JOptionPane.showMessageDialog(null, "Operación realizada.");
                }
                else{
                    //this.view.setStatusMessageLabel("Error al crear el test", Color.RED);
                    JOptionPane.showMessageDialog(null,"Error al cargar el test.","Error",JOptionPane.ERROR_MESSAGE);
                }
            } 
            catch (ClassNotFoundException ex) {}
            catch (SQLException ex) {System.out.println(ex);}
            
    }
    else{
        //this.view.setStatusMessageLabel("Error, compruebe los formularios.", Color.red);
        JOptionPane.showMessageDialog(null,"Error, compruebe los formularios.","Error",JOptionPane.ERROR_MESSAGE);
    }
}//GEN-LAST:event_btnCrearTestActionPerformed

    private void btnAddPreguntaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddPreguntaActionPerformed
        //el arbol esta vacio
        if (!preguntasTestTree.isEnabled()){
            try {
                top = new DefaultMutableTreeNode("Temas");
                createNodesPreguntasTest(top);
                DefaultTreeModel modelo = new DefaultTreeModel(top);
                preguntasTestTree.setModel(modelo);
            } catch (SQLException ex) {
            } catch (ClassNotFoundException ex) {
            }
        }
        //el arbol no esta vacio
        else{
            try {
                createNodesPreguntasTest(top);
                DefaultTreeModel modelo = new DefaultTreeModel(top);
                preguntasTestTree.setModel(modelo);
            } catch (SQLException ex) {
            } catch (ClassNotFoundException ex) {
            }
        }
        preguntasTestTree.setEnabled(true);
        repaint();
        for (int i = 0; i < preguntasTestTree.getRowCount(); i++) {
            preguntasTestTree.expandRow(i);
        }
        
    }//GEN-LAST:event_btnAddPreguntaActionPerformed

    private void btnDeletePreguntaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeletePreguntaActionPerformed
        deleteSelectedItems();
        for (int i = 0; i < preguntasTestTree.getRowCount(); i++) {
            preguntasTestTree.expandRow(i);
        }
    }//GEN-LAST:event_btnDeletePreguntaActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAddPregunta;
    private javax.swing.JButton btnCrearTest;
    private javax.swing.JButton btnDeletePregunta;
    private javax.swing.JComboBox cbAsignaturas;
    private datechooser.beans.DateChooserCombo dcFechaFin;
    private datechooser.beans.DateChooserCombo dcFechaInicio;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTree jTree1;
    private javax.swing.JLabel lbAsignatura;
    private javax.swing.JLabel lbDescripcion;
    private javax.swing.JLabel lbFechaFin;
    private javax.swing.JLabel lbFechaInicio;
    private javax.swing.JLabel lbHoraFin;
    private javax.swing.JLabel lbHoraInicio;
    private javax.swing.JLabel lbNombre;
    private javax.swing.JTree preguntasTestTree;
    private javax.swing.JSpinner spHoraFin;
    private javax.swing.JSpinner spHoraInicio;
    private javax.swing.JTree temasTree;
    private javax.swing.JTextArea txtDescripcion;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables

    private void createNodesTemas(DefaultMutableTreeNode top) {
        top = new DefaultMutableTreeNode("Temas");
        DefaultMutableTreeNode tema = null;
        DefaultMutableTreeNode pregunta = null;

        if (this.profesor.getAsignaturas() != null) {
            Asignatura asig = (Asignatura) cbAsignaturas.getSelectedItem();

            if(!asig.getTemas().isEmpty()){
                for (Tema tem : asig.getTemas()) {
                    tema = new DefaultMutableTreeNode(tem);
                    top.add(tema);
                    if(!tem.getPreguntas().isEmpty())
                        for (Pregunta preg : tem.getPreguntas()) {
                            pregunta = new DefaultMutableTreeNode(preg);
                            tema.add(pregunta);
                        }
                    }
                }
            }
        DefaultTreeModel modelo = new DefaultTreeModel(top);
        temasTree.setModel(modelo);
    }
    
    private void createNodesPreguntasTest(DefaultMutableTreeNode top) throws SQLException, ClassNotFoundException {
        TreePath[] paths = temasTree.getSelectionPaths();
        DefaultMutableTreeNode tema = null;
        DefaultMutableTreeNode pregunta = null;
        HashMap<Tema,List<Pregunta>> mapa = new HashMap<Tema,List<Pregunta>>();

        //guardo los multiples árboles seleccionados en un Map
        for (TreePath t : paths){
            if (t.getPathCount() == 3){
                DefaultMutableTreeNode dmt = (DefaultMutableTreeNode) t.getPathComponent(1);
                Tema taux = (Tema) dmt.getUserObject();
                dmt = (DefaultMutableTreeNode) t.getPathComponent(2);
                Pregunta paux = (Pregunta) dmt.getUserObject();
            
                if(mapa.containsKey(taux)){
                    mapa.get(taux).add(paux);
                }
                else{
                    ArrayList<Pregunta> listaPreg = new ArrayList<Pregunta>();
                    listaPreg.add(paux);
                    mapa.put(taux, listaPreg);
                }
            }
            else if (t.getPathCount() == 2){
                DefaultMutableTreeNode dmt = (DefaultMutableTreeNode) t.getPathComponent(1);
                Tema taux = (Tema) dmt.getUserObject();
                List<Pregunta> listaPreg = fachada.seleccionarPreguntas(taux);
                mapa.put(taux, listaPreg);
            }
        }
    
        //Creo los nodos a partir del map
        for(Tema t : mapa.keySet()){
            tema = searchNode(t.toString());
            if(tema == null)  { tema = new DefaultMutableTreeNode(t);top.add(tema);}
            
            for(Pregunta p : mapa.get(t)){
                pregunta = searchNode(p.toString());
                if(pregunta == null) { pregunta = new DefaultMutableTreeNode(p); tema.add(pregunta);}
            }
        }
        
    }
    
    /**
     * Crea u conjunto de preguntas.
     * @param tree
     * @return Un conjunto de preguntas
     */
    public Set<Pregunta> createSet(JTree tree) {
        Set<Pregunta> setPregs = new HashSet<Pregunta>();
        
        int numRows = tree.getRowCount();
        TreePath[] paths = new TreePath[numRows];
        for(int i=0; i<numRows; i++){
                paths[i] = tree.getPathForRow(i);
            }

        tree.clearSelection();

        for (TreePath t : paths){
            if (t.getPathCount() == 3){
                DefaultMutableTreeNode dmt = (DefaultMutableTreeNode) t.getLastPathComponent();
                Pregunta preg = (Pregunta) dmt.getUserObject();
                setPregs.add(preg);
                }
            }
        return setPregs;
    }
    
    /**
     * Borrar items seleccionados
     */
    public void deleteSelectedItems() {
        DefaultMutableTreeNode node;
        DefaultTreeModel model = (DefaultTreeModel) (preguntasTestTree.getModel());
        TreePath[] paths = preguntasTestTree.getSelectionPaths();
        for (int i = 0; i < paths.length; i++) {
            node = (DefaultMutableTreeNode) (paths[i].getLastPathComponent());
            if (node.getParent().getChildCount() == 1){
                node = (DefaultMutableTreeNode) (paths[i].getPathComponent(1));
                model.removeNodeFromParent(node);
            }
            else{
                model.removeNodeFromParent(node);
            }
        }
    }
    
        
    /**
     * Buscar nodo
     * @param nodeStr
     * @return Un nodo del árbol.
     */
    public DefaultMutableTreeNode searchNode(String nodeStr)
    {
        DefaultMutableTreeNode node = null;
        
        //Get the enumeration
        Enumeration en = this.top.breadthFirstEnumeration();
        
        //iterate through the enumeration
        while(en.hasMoreElements())
        {
            //get the node
            node = (DefaultMutableTreeNode)en.nextElement();
            
            //match the string with the user-object of the node
            if(nodeStr.equals(node.getUserObject().toString()))
            {
                //tree node with string found
                return node;                         
            }
        }
        
        //tree node with string node found return null
        return null;
    } 
    
    private boolean  checkFields() {
        Calendar hoy = Calendar.getInstance();
        
        Calendar inicio = dcFechaInicio.getSelectedDate();
        Date horaInicio = (Date) spHoraInicio.getValue();
        Calendar aux = Calendar.getInstance();
        aux.setTimeInMillis(horaInicio.getTime());
        int hora = aux.get(Calendar.HOUR_OF_DAY);
        int minuto = aux.get(Calendar.MINUTE);
        inicio.set(Calendar.HOUR_OF_DAY, hora);
        inicio.set(Calendar.MINUTE, minuto);
        inicio.set(Calendar.SECOND, hoy.get(Calendar.SECOND));
        inicio.set(Calendar.MILLISECOND, hoy.get(Calendar.MILLISECOND));
        
        Calendar fin = dcFechaFin.getSelectedDate();
        Date horaFin = (Date) spHoraFin.getValue();
        aux.setTimeInMillis(horaFin.getTime());
        hora = aux.get(Calendar.HOUR_OF_DAY);
        minuto = aux.get(Calendar.MINUTE);
        fin.set(Calendar.HOUR_OF_DAY, hora);
        fin.set(Calendar.MINUTE, minuto);
        fin.set(Calendar.SECOND, hoy.get(Calendar.SECOND));
        fin.set(Calendar.MILLISECOND, hoy.get(Calendar.MILLISECOND));

        dateInicio = new Timestamp(inicio.getTimeInMillis());
        dateFin = new Timestamp(fin.getTimeInMillis());
        
//        System.out.println("INI: "+inicio.get(Calendar.DAY_OF_MONTH)+" " +inicio.get(Calendar.HOUR_OF_DAY)+":"+inicio.get(Calendar.MINUTE)+":"+inicio.get(Calendar.SECOND)+":"+inicio.get(Calendar.MILLISECOND));
//        System.out.println("HOY: "+hoy.get(Calendar.DAY_OF_MONTH)+" "+hoy.get(Calendar.HOUR_OF_DAY)+":"+hoy.get(Calendar.MINUTE)+":"+hoy.get(Calendar.SECOND)+":"+hoy.get(Calendar.MILLISECOND));
//        System.out.println("FIN: "+fin.get(Calendar.DAY_OF_MONTH)+" "+fin.get(Calendar.HOUR_OF_DAY)+":"+fin.get(Calendar.MINUTE)+":"+fin.get(Calendar.SECOND)+":"+fin.get(Calendar.MILLISECOND));
//        
        if( (txtDescripcion.getText().isEmpty()) || (txtNombre.getText().isEmpty())){
            return false;
        }
        else if( (inicio.before(hoy)) || (fin.before(inicio))) {
            return false;
        }
        else{
            return true;
        }
    }

    /**
     * Establece lenguaje
     */
    public void setLenguaje() {
        setTitle(Messages.getString("Form.title", Messages.BUNDLE_NAME_CREAR_TEST));
        btnAddPregunta.setText(Messages.getString("btnAddPregunta.text", Messages.BUNDLE_NAME_CREAR_TEST));
        btnCrearTest.setText(Messages.getString("btnCrearTest.text", Messages.BUNDLE_NAME_CREAR_TEST));
        btnDeletePregunta.setText(Messages.getString("btnDeletePregunta.text", Messages.BUNDLE_NAME_CREAR_TEST));
        dcFechaFin.setDateFormat(Messages.getDateFormat());
        dcFechaInicio.setDateFormat(Messages.getDateFormat());
//        jTree1;
        lbAsignatura.setText(Messages.getString("lbAsignatura.text", Messages.BUNDLE_NAME_CREAR_TEST));
        lbDescripcion.setText(Messages.getString("lbDescripcion.text", Messages.BUNDLE_NAME_CREAR_TEST));
        lbFechaFin.setText(Messages.getString("lbFechaFin.text", Messages.BUNDLE_NAME_CREAR_TEST));
        lbFechaInicio.setText(Messages.getString("lbFechaInicio.text", Messages.BUNDLE_NAME_CREAR_TEST));
        lbHoraFin.setText(Messages.getString("lbHoraFin.text", Messages.BUNDLE_NAME_CREAR_TEST));
        lbHoraInicio.setText(Messages.getString("lbHoraInicio.text", Messages.BUNDLE_NAME_CREAR_TEST));
        lbNombre.setText(Messages.getString("lbNombre.text", Messages.BUNDLE_NAME_CREAR_TEST));
//        preguntasTestTree;
//        spHoraFin;
//        spHoraInicio;
//        temasTree;
//        temasTree.setRootVisible(false);
//        preguntasTestTree.setRootVisible(false);
    }
}


// Esto esta aqui por si Netbeans me toca los huevos y lo borra de initComponents()
//        hora_inicio = new JSpinner( new SpinnerDateModel() );
//	JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(hora_inicio, "HH:mm a");
//	hora_inicio.setEditor(timeEditor);
//	hora_inicio.setValue(new Date()); 
//	hora_fin = new JSpinner( new SpinnerDateModel() );
//	JSpinner.DateEditor timeEditor2 = new JSpinner.DateEditor(hora_fin, "HH:mm a");
//	hora_fin.setEditor(timeEditor2);
//	hora_fin.setValue(new Date());

//		JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(spHoraInicio, "HH:mm a");
//		sp_HoraInicio.setEditor(timeEditor);
//		spHoraInicio.setValue(new Date()); 
//		
//		JSpinner.DateEditor timeEditor2 = new JSpinner.DateEditor(spHoraFin, "HH:mm a");
//		spHoraFin.setEditor(timeEditor2);
//		spHoraFin.setValue(new Date());
